{% from "webshop/templates/includes/macros.html" import user_review, ratings_summary %}

<div class="mt-4 ratings-reviews-section">
		<!-- Title and Action -->
		<div class="w-100 mt-4 mb-2 d-flex">
			<div class="reviews-header col-9">
				{{ _("Customer Reviews") }}
			</div>

			<div class="write-a-review-btn col-3">
				<!-- Write a Review for legitimate users -->
				{% if frappe.session.user != "Guest" and user_is_customer %}
					<button class="btn btn-write-review"
						data-web-item="{{ doc.name }}">
						{{ _("Write a Review") }}
					</button>
				{% endif %}
			</div>
		</div>

		<!-- Summary -->
		{{ ratings_summary(reviews, reviews_per_rating, average_rating, average_whole_rating, for_summary=True, total_reviews=total_reviews) }}


	<!-- Reviews and Comments -->
	<div class="mt-8">
		{% if reviews %}
			{{ user_review(reviews) }}

			{% if total_reviews > 4 %}
				<div class="mt-6 mb-6"style="color: var(--primary);">
					<a href="/customer_reviews?web_item={{ doc.name }}">{{ _("View all reviews") }}</a>
				</div>
			{% endif %}

		{% else %}
			<h6 class="text-muted mt-6">
				{{ _("No Reviews") }}
			</h6>
		{% endif %}
	</div>
</div>

<script>
	frappe.ready(() => {
		$('.page_content').on('click', '.btn-write-review', (e) => {
			// Bind action on write a review button
			const $btn = $(e.currentTarget);

			let d = new frappe.ui.Dialog({
				title: __("Write a Review"),
				fields: [
					{fieldname: "title", fieldtype: "Data", label: "Headline", reqd: 1},
					{fieldname: "rating", fieldtype: "Rating", label: "Overall Rating", reqd: 1},
					{fieldtype: "Section Break"},
					{fieldname: "comment", fieldtype: "Small Text", label: "Your Review"}
				],
				primary_action: function() {
					var data = d.get_values();
					frappe.call({
						method: "webshop.webshop.doctype.item_review.item_review.add_item_review",
						args: {
							web_item: "{{ doc.name }}",
							title: data.title,
							rating: data.rating,
							comment: data.comment
						},
						freeze: true,
						freeze_message: __("Submitting Review ..."),
						callback: function(r) {
							if(!r.exc) {
								frappe.msgprint({
									message: __("Thank you for the review"),
									title: __("Review Submitted"),
									indicator: "green"
								});
								d.hide();
								location.reload();
							}
						}
					});
				},
				primary_action_label: __('Submit')
			});
			d.show();
		});
	});
</script>
